import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import FieldList from '../FieldList';
import ContacterListForCard from '../ContacterList';
import CardHearder from '../../public/CardHearder';
import { Card, WhiteSpace, Icon, ActionSheet, ActivityIndicator, Result, Tools, PullToRefresh, Modal } from 'weaver-mobile';
import { RouteLayout, ListViewPage, TabPage,Share } from 'weaver-mobile-page';

import ContacterForm from '../../form/ContacterForm';
import ContacterList from '../../list/ContacterList';
import ContacterCard from '../../card/Contacter';
import CustomerCard from '../../card/Customer';
import CustomerShareList from '../../list/CustomerShareList';
import SellChanceShareList from '../../list/SellChanceShareList';
import ContactList from '../../list/ContactList';
import ChanceViewAndEdit from '../../form/ChanceViewAndEdit'
import ChanceCardStore from '../../../stores/card/ChanceCardStore';
import CrmResult from '../CrmResult'
import NoRight from '../../public/NoRight';
const alert = Modal.alert;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
const getLabel = Tools.getLabel;
// @inject('chanceCardStore')
@withRouter
@observer
export default class ChanceCard extends Component {
  constructor(props) {
    // console.log(props)
    super(props);
    this.state = {
      store: new ChanceCardStore(),
      span: [7, 1],
      curContacterId: "",
      showAddContact: false,
      paramsnew:{},
    }
  }

  componentWillMount() {
    const { match, params } = this.props;
    const ps = params ? params : match.params;
    const store = this.state.store;
    let psnew = this.dealWithParam(ps);
    store.doNew(this, psnew);
    this.setState({
      paramsnew:psnew
    })
  }
  dealWithParam = (ps)=>{
    let psbak = {};
    if(ps.id.lastIndexOf("moduleid")>-1 &&ps.id.lastIndexOf("em_auth_userid") > -1){
      let strs= new Array(); 
      strs=ps.id.split("&"); 
      psbak.id = strs[0];
      for (let i=1;i<strs.length ;i++ ) { 
        let param= new Array(); 
        param=strs[i].split("=");  
        if(param.length >=2){
          psbak[param[0]] = param[1];
        }          
      } 
    }else{
       if("id" in ps){
        psbak.id = ps.id;
      } 
    }
    
    return psbak;
  
  }
  componentDidMount() {
    // const {chanceCardStore} = this.props;
    const store = this.state.store;
    store.doInit();
  }

  componentWillUnmount() {
    // const { chanceCardStore } = this.props;
    const store = this.state.store;
    store.doClear();
  }

  render() {
    // const store = this.props.chanceCardStore;
    const store = this.state.store;
    const { initResponsed, initSuccessed, initFailedMsg } = store;
    if (initResponsed) {
      if (initSuccessed) {
        const { span, curContacterId, showAddContact } = this.state;
        const { canEdit, tabs, refreshing, fieldItems, contacterItems, 
          contacterCount, chanceId, chanceName, chanceManager, chanceOthers, 
          chanceConcerned, customerId, tabPage, contacterListLayout, customerCardLayout, 
          contacterCardLayout, shareListLayout, createContacterLayout, contactListStore, chanceViewAndEditLayout, isPro ,creater,
          shareSellChanceLayout,shareStore,userId,onlyView} = store;
        const tabProps = {
          page: tabPage,
          swipeable: true,
          onChange: (tab) => {
            store.tabChange(tab.key);
          },
        };
          return (
            <div className="crm-card-base">
              <CardHearder
                title1={chanceName}
                title2={`<div onclick="javascript:window.openLink.openHrm(${creater});">${chanceManager}</div>`}
                // <div class="crm_phone" onclick="javascript:window.openLink.openHrm(${creater});">{chanceManager}</div>
                title3={chanceOthers}
                concerned={chanceConcerned}
                showConcerned={!onlyView?true:false}
                showMore={false}
                concernedClick={this.concernedClick.bind(this)}
                moreClick={this.moreClick.bind(this)} />
              <div className="crm-card-content">
                {/* <Tabs tabs={tabs}
                  initialPage={tabPage}
                  renderTab={tab => <span>{tab.title}</span>}
                  page={tabPage}
                  onChange={
                    (TabData, index)=>{
                      store.tabChange(index);
                    }
                  }
                /> */}
                <TabPage
                  span={span}
                  tabs={tabs}
                  tabProps={tabProps}
                  btns={!onlyView?[<Icon type="ellipsis" onClick={this.moreClick.bind(this)} />]:[]}
                // defaultTabBarProps={{ page: 1}}
                // popover={false}
                // popoverProps={popoverProps}
                />
                <WhiteSpace />
                {
                  tabPage == "info" && (
                    <div className="crm-card-main">
                      <PullToRefresh
                        damping={60}
                        // ref={el => this.ptr = el}
                        style={{
                          height: "100%",
                          overflow: 'auto',
                        }}
                        direction={'down'}
                        refreshing={refreshing}
                        onRefresh={() => {
                          store.doInit();
                        }}
                      >
                        <Card full>
                          <Card.Header
                            title={<span style={{ marginLeft: "5px", whiteSpace: "nowrap" }}>{getLabel('24893', '基础信息')}</span>}
                            extra={<span></span>}
                          >
                          </Card.Header>
                          <Card.Body>
                            <FieldList fieldItems={fieldItems} iconClick={this.iconClick.bind(this)} />
                            <div className="crm-field-item-bottom"></div>
                          </Card.Body>
                          <Card.Footer content={
                            <div className="crm-card-footer" onClick={() => {
                              this.props.history.push(chanceViewAndEditLayout.path);
                            }}>
                              <div>{getLabel('1293', '查看详细信息')}</div>
                              <div className="crm-field-item-operate"><Icon type={"right"} /></div>
                            </div>
                          } />
                        </Card>
                        <WhiteSpace />
                        <Card full>
                          <Card.Header
                            title={<span style={{ marginLeft: "5px" }}>{getLabel('572', '联系人')}</span>}
                            extra={
                              (canEdit && <span><i className='crm-card-bar-icon icon-crm icon-crm-add' onClick={
                                () => {
                                  this.props.history.push(createContacterLayout.path);
                                }
                              } /></span>)
                            }
                          >
                          </Card.Header>
                          <Card.Body>
                            <ContacterListForCard contacterItems={contacterItems} onContacterClick={this.onContacterClick.bind(this)} />
                          </Card.Body>
                          <Card.Footer content={
                            <div className="crm-card-footer" onClick={() => {
                              this.props.history.push(contacterListLayout.path);
                            }}>
                              <div>{getLabel('390916', "查看全部联系人")}&nbsp;&nbsp;|&nbsp;&nbsp;{contacterCount}</div>
                              <div className="crm-field-item-operate"><Icon type={"right"} /></div>
                            </div>
                          } />
                        </Card>
                      </PullToRefresh>
                    </div>
                  )
                }
                {
                  tabPage == "contact" && (
                    <div className="crm-card-list">
                      <ContactList params={{ customerId: customerId, chanceId: chanceId }} onRef={this.onRef} showAddContact={showAddContact}></ContactList>
                    </div>
                  )
                }
              </div>
              <Route
                key={contacterListLayout.id}
                path={contacterListLayout.path}
                render={() => {
                  // 查看全部联系人
                  let detailContent = <ContacterList params={{ id: customerId }} />
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="contacterListLayout"
                        className="wm-route-layout"
                      >
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
              <Route
                key={contacterCardLayout.id}
                path={contacterCardLayout.path}
                render={() => {
                  // 联系人卡片
                  let detailContent = <ContacterCard params={{ id: curContacterId }} cardStore={store} />
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="contacterCardLayout"
                        className="wm-route-layout"
                      >
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
              <Route
                key={createContacterLayout.id}
                path={createContacterLayout.path}
                render={() => {
                  // 新建联系人
                  let detailContent = <ContacterForm cardStore={store} params={{ operation: "add", customerId: customerId }} />
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="createContacterLayout"
                        className="wm-route-layout"
                      >
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
              <Route
                key={shareListLayout.id}
                path={shareListLayout.path}
                render={() => {
                  // 查看共享
                  let detailContent = <SellChanceShareList params={{ id: chanceId }} />
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="shareListLayout"
                        className="wm-route-layout"
                      >
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
              <Route
                key={customerCardLayout.id}
                path={customerCardLayout.path}
                render={() => {
                  // 客户卡片
                  let detailContent = <CustomerCard params={{ id: customerId }} store={store} />
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="customerCardLayout"
                        className="wm-route-layout"
                      >
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />

              <Route
                key={chanceViewAndEditLayout.id}
                path={chanceViewAndEditLayout.path}
                render={() => {
                  // 商机详情和编辑
                  let detailContent = <ChanceViewAndEdit emparams={{...this.state.paramsnew}} params={{ sellChanceId: chanceId, customerId: customerId, chanceName: chanceName, canEdit: canEdit, isPro: isPro }} cardStore={this.props.cardStore} />
                  return (
                    <RouteLayout getContainer={() => document.getElementById("root")}>
                      <div
                        key="chanceViewAndEditLayout"
                        className="wm-route-layout"
                      >
                        {detailContent}
                      </div>
                    </RouteLayout>
                  )
                }}
              />
            {/* 分享 */}
            <Route
                  key={shareSellChanceLayout.id}
                  path={shareSellChanceLayout.path}
                  render={() => {
                    let shareDialog = 
                    <Share        
                          shareParams={ {
                            'resourcetype' : "316",
                            'resourceid' : chanceId
                          }
                          }
                          store={shareStore }
                          msgInfo={{
                            'content': chanceName, // 分享标题（必填）
                            'sysid': window.localStorage.emobile_ec_id, //EM中添加的集成系统的ID (必填: 按照demo给的传)             
                            //'desc': "客户啊啊啊", // 分享描述（非必填）
                            'linkurl':`/common/chatResource/view.html?resourcetype=316&resourceid=${chanceId}&isfromchatshare=1&sharer=${userId}&firstSharer=${userId}&moduleid=em`,// 消息链接地址（必填） // 消息链接地址（必填）
                            //'linkurl_pc':"/viewrequest.jsp?id=123", //PC端消息链接地址，如果没有则取linkurl值
                            'canforward':1, // 消息是否允许转发 1：是（默认） 0：否
                            'callbackurl':"/api/common/chatResource/addshare?resourcetype=316&resourceid="+chanceId+"&isfromchatshare=1&firstSharer="+userId, // 消息转发回调地址（非必填）
                            'sharetypename':getLabel(520327,"商机名片"), //消息类型显示标题，没有则按sharetype显示
                            'opentype':1, //移动端打开方式 1:app内打开（默认） 2：手机默认浏览器打开
                            'opentype_pc':2, //PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                            'sharetype':"crm", // 分享数据类型："doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
                            'shareid':chanceId // 分享的数据ID（必填）
                          
                          } 
                        }                                                           
                    />
                    return (
                      <RouteLayout getContainer={() => document.getElementById("root")}>
                        <div
                          key="shareSellChanceLayout"
                          className="wm-route-layout"
                        >
                          {shareDialog}
                        </div>
                      </RouteLayout>
                    )
                  }}
                />
                {/* end */}
            </div>
          );
      } else {
        return (
           <NoRight />
          // <div>
          //   <CrmResult
          //     message={initFailedMsg}
          //   />
          // </div>
          
          );
      }
    } else {
      return <div className="crm-bg-loading"><ActivityIndicator text="Loading..." /></div>;
    }
  }

  onRef = (ref) => {
    this.contactListRef = ref;
  }

  // 客户信息操作
  iconClick(itemKey, title, value, valueSpan) {
    // const store = this.props.chanceCardStore;
    const store = this.state.store;
    if (itemKey == 5) {
      const { customerCardLayout } = store;
      this.props.history.push(customerCardLayout.path);
    }
  }

  // 关注 or 取消关注
  concernedClick(concerned) {
    // const store = this.props.chanceCardStore;
    const store = this.state.store;
    store.setChanceConcerned(concerned);
  }

  onContacterClick(id) {
    // const store = this.props.customerCardStore;
    this.setState({ curContacterId: id });
    const store = this.state.store;
    const { contacterCardLayout } = store;
    this.props.history.push(contacterCardLayout.path);
  }

  moreClick() {
    // const store = this.props.chanceCardStore;
    const store = this.state.store;
    const { customerId, shareListLayout, tabPage, doDelete, canEdit, isPro ,canShare,shareSellChanceLayout} = store;
    let btns = [];
    // console.log(canEdit)
    btns.push({ content: getLabel('390921', "添加联系记录") });
    if (canEdit && !isPro) {
      btns.push({ content: getLabel('501297', "删除商机") });
      btns.push({ content: getLabel('30832', '查看共享') });
    }

    if(canShare){
      btns.push({key:3, content: getLabel('126091', "分享") });
    }

    btns.push({content: getLabel('201', '取消') });
    ActionSheet.showActionSheetWithOptions({
      options: btns,
      cancelButtonIndex: btns.length - 1,
      maskClosable: true,
      'data-seed': 'logId',
      wrapProps,
    },
      (buttonIndex) => {
        // console.log("buttonIndex",buttonIndex);
        if (buttonIndex == 0) {
          // 添加联系记录
          if (tabPage != "contact") {
            store.tabChange("contact");
            this.setState({ showAddContact: true });
            setTimeout(() => {
              this.setState({ showAddContact: false });
            }, 100);
          } else {
            this.contactListRef.addContact();
          }
        }
        if (canEdit) {
          if (!isPro) {
            if (buttonIndex === 1) {
              //删除商机
              alert('', getLabel('83600', '您确认要删除吗？'), [
                { text: getLabel('201', '取消'), onPress: () => { } },
                { text: getLabel('83446', '确定'), onPress: () => { doDelete(); } },
              ]);
            }
          }
          if (buttonIndex === 2) {
            this.props.history.push(shareListLayout.path);
          }
        }
        
        if(canShare){
            if(btns[buttonIndex].key == 3){
              this.props.history.push(shareSellChanceLayout.path);
            }

        }

      });
  }
}